package com.kzc.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

public class DBUtil {

	static Connection conn = null;
	static PreparedStatement pst = null;
	static ResultSet rs = null;
	
	/**获取数据库连接*/	
	public static Connection getConnection() throws Exception {
	//	Connection connection = DriverManager.getConnection("jdbc:odbc:Driver={MicroSoft Access Driver (*.mdb)};DBQ=C:/Windows/System32/test1.mdb","dba","sql");  
		
		Class.forName("com.mysql.jdbc.Driver");
		Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/amanda","root", "mysql");
		return connection; 
	}


	/**关闭数据库连接*/
	public static void closeConnection(Connection conn, Statement st,
			ResultSet rs) {
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (pst != null) {
			try {
				pst.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**进行添加数据操作*/
	public static boolean add(String sql,List<Object> values){
		boolean bl = false;
		try {
			conn = getConnection();
			pst = conn.prepareStatement(sql);
			for (int i = 0; i < values.size(); i++) {
				pst.setObject(i+1, values.get(i));
			}
			bl = (pst.executeUpdate() == 1);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBUtil.closeConnection(conn, pst, null);
		}
		return bl;
	}
	
	/**进行删除数据操作*/
	public static boolean delete(String sql,List<Object> values){
		boolean bl = false;
		try {
			conn = getConnection();
			pst = conn.prepareStatement(sql);
			for (int i = 0; i < values.size(); i++) {
				pst.setObject(i+1, values.get(i));
			}
			bl = (pst.executeUpdate() == 1);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBUtil.closeConnection(conn, pst, null);
		}
		return bl;
	}
	
	/**进行修改操作*/
	public static boolean update(String sql,List<Object> values){
		boolean bl = false;
		try {
			conn = getConnection();
			pst = conn.prepareStatement(sql);
			for (int i = 0; i < values.size(); i++) {
				pst.setObject(i+1, values.get(i));
			}
			bl = (pst.executeUpdate() == 1);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBUtil.closeConnection(conn, pst, null);
		}
		return bl;
	}
	
	/**进行查询操作*/
	public static ResultSet query(String sql,List<Object> values){
		try {
			conn = getConnection();
			pst = conn.prepareStatement(sql);
			for (int i = 0; i < values.size(); i++) {
				pst.setObject(i+1, values.get(i));
			}
			rs = pst.executeQuery();
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return rs;
	}
}
